package com.wxl.common.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import com.luck.picture.lib.tools.SPUtils;
import com.wxl.common.BuildConfig;

public class DeviceUtil {


    /**
     * 获取设备存储的时间，用于判断当前小于的异常
     * @return
     */
    public static long getDeviceTime() {
        long time = SPUtils.getInstance().getLong("deviceTime",0);
        if (time == 0) {
            time = SerialUtil.getTime(BuildConfig.apkBuildTime);
            SPUtils.getInstance().put("deviceTime", time);
        }
        return time;
    }

    /**
     * 设置设备存储时间
     */
    public static void setDeviceTime(long time) {
        SPUtils.getInstance().put("deviceTime", time);
    }


    /**
     * 获取当前的versioncode
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();//context为当前Activity上下文
            pi = pm.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return pi.versionName;
    }

    /**
            * 获取手机IMEI(需要“android.permission.READ_PHONE_STATE”权限)
     *
             * @return  手机IMEI
     */
    public static String getIMEI(Context ctx) {
        TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Activity.TELEPHONY_SERVICE);
        if (tm != null) {
            return tm.getDeviceId();
        }
        return null;
    }


    /**
     * 更新设备时间
     * @param ctx
     */
    public static void updateDeviceTime(Context ctx){
        // 自动更新时间且网络可用，则保存时间
        if (Settings.System.getInt(ctx.getContentResolver(), Settings.System.AUTO_TIME, 0) == 1 && NetWorkUtils.isNetWorkUse(ctx)) {
            long time = System.currentTimeMillis();
            DeviceUtil.setDeviceTime(time);
        }
    }
}
